<template>
  <div class="search-page">
    <div class="search-container">
      <div class="search-box">
        <div class="search-input-container">
          <div class="search-tags">
            <div 
              v-for="(tag, index) in searchTags" 
              :key="index" 
              class="search-tag"
            >
              {{ tag }}
              <span class="remove-tag" @click="removeTag(index)">&times;</span>
            </div>
            <input 
              v-model="currentInput"
              placeholder="输入标签或描述搜索视频..."
              @input="handleInput"
              @keydown.backspace="handleBackspace"
              @keydown.enter="addTag"
              @keydown.space.prevent="addTag"
              class="tag-input"
              ref="inputRef"
            />
          </div>
        </div>
        <button @click="openVideoFile" class="open-button">
          打开视频
        </button>
      </div>
      <div class="search-results" v-if="hasSearchResults">
        <div 
          v-for="video in groupedResults" 
          :key="video.path"
          class="video-card"
          @click="openVideo(video)"
        >
          <div class="video-thumbnail">
            <video :src="`safe-file://${video.path}`" preload="metadata">
              <track kind="captions">
            </video>
          </div>
          <div class="video-info">
            <h3>{{ video.name }}</h3>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useVideoStore } from '../stores/videoStore'
import { openDatabase } from '../../db/init'
import debounce from 'lodash/debounce'
import { v4 as uuidv4 } from 'uuid'
import log from 'electron-log'

const remote = window.require('@electron/remote')
const { dialog } = remote

const videoStore = useVideoStore()
const searchTags = ref([])
const currentInput = ref('')
const inputRef = ref(null)

const hasSearchResults = computed(() => {
  return searchTags.value.length > 0 && groupedResults.value.length > 0
})

const groupedResults = computed(() => {
  if (!searchTags.value.length) return []
  
  const groups = {}
  const queries = searchTags.value.map(tag => tag.toLowerCase())
  
  // 按视频路径分组标签
  videoStore.allTags.forEach(tag => {
    if (!groups[tag.video_path]) {
      groups[tag.video_path] = {
        path: tag.video_path,
        name: tag.video_path.split(/[\\/]/).pop(),
        tags: new Set() // 使用 Set 来存储唯一的标签名
      }
    }
    groups[tag.video_path].tags.add(tag.name.toLowerCase())
  })

  // 过滤出包含所有搜索标签的视频
  return Object.values(groups).filter(video => {
    const tagSet = video.tags
    return queries.every(query => 
      Array.from(tagSet).some(tagName => tagName.includes(query))
    )
  })
})

// 恢复搜索状态
const restoreSearchState = () => {
  searchTags.value = [...videoStore.searchState.tags]
  currentInput.value = videoStore.searchState.currentInput
  if (searchTags.value.length > 0) {
    handleInput()
  }
}

const handleInput = debounce(() => {
  videoStore.searchTags(searchTags.value.join(' '))
  // 保存搜索状态
  videoStore.saveSearchState(searchTags.value, currentInput.value)
}, 300)

const addTag = () => {
  const value = currentInput.value.trim()
  if (value && !searchTags.value.includes(value)) {
    searchTags.value.push(value)
    currentInput.value = ''
    handleInput()
  }
}

const removeTag = (index) => {
  searchTags.value.splice(index, 1)
  handleInput()
}

const handleBackspace = (event) => {
  if (currentInput.value === '' && searchTags.value.length > 0) {
    event.preventDefault()
    searchTags.value.pop()
    handleInput()
  }
}

const openVideo = async (video) => {
  videoStore.currentVideo = {
    path: `safe-file://${video.path}`,
    name: video.name,
    originalPath: video.path
  }
  await videoStore.loadTags(video.path)
  await videoStore.updateVideoInfo(video.path)
  videoStore.setCurrentPage('player')
}

const openVideoFile = async () => {
  try {
    const result = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: [
        { name: '视频文件', extensions: ['mp4', 'webm', 'mkv'] }
      ]
    })

    if (!result.canceled && result.filePaths.length > 0) {
      const filePath = result.filePaths[0]
      const name = filePath.split(/[\\/]/).pop()
      
      // 创建视频记录
      const db = await openDatabase()
      
      // 先检查视频是否已存在
      let video = db.prepare('SELECT id FROM videos WHERE path = ?').get(filePath)
      
      if (!video) {
        // 如果视频不存在，创建新记录
        const videoId = uuidv4()
        db.prepare(`
          INSERT INTO videos (id, path, name, last_accessed)
          VALUES (?, ?, ?, CURRENT_TIMESTAMP)
        `).run(videoId, filePath, name)
        video = { id: videoId }
      } else {
        // 如果视频存在，更新访问时间
        db.prepare(`
          UPDATE videos 
          SET last_accessed = CURRENT_TIMESTAMP
          WHERE id = ?
        `).run(video.id)
      }
      
      // 设置当前视频并加载标签
      videoStore.currentVideo = {
        path: `safe-file://${filePath}`,
        name,
        originalPath: filePath
      }
      await videoStore.loadTags(filePath)
      videoStore.setCurrentPage('player')
    }
  } catch (error) {
    log.error('打开文件对话框时出错:', error)
  }
}

onMounted(() => {
  restoreSearchState()
  videoStore.searchTags(searchTags.value.join(' '))
})
</script>

<style scoped>
.search-page {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: #f5f5f5;
  padding: 40px 20px;
}

.search-container {
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-input-container {
  flex: 1;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 4px 8px;
  transition: border-color 0.2s;
}

.search-input-container:focus-within {
  border-color: #1976d2;
}

.search-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
  min-height: 36px;
}

.search-tag {
  display: flex;
  align-items: center;
  background: #e3f2fd;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
  color: #1976d2;
  gap: 4px;
}

.remove-tag {
  cursor: pointer;
  font-size: 16px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  color: #1976d2;
  transition: background-color 0.2s;
}

.remove-tag:hover {
  background-color: #bbdefb;
}

.tag-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 14px;
  padding: 4px;
  min-width: 100px;
  background: transparent;
}

.open-button {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  background: #1976d2;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  white-space: nowrap;
}

.open-button:hover {
  background: #1565c0;
}

.search-results {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}

.video-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.video-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.video-thumbnail {
  width: 100%;
  aspect-ratio: 16 / 9;
  background: #000;
  position: relative;
  overflow: hidden;
}

.video-thumbnail video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  position: absolute;
  top: 0;
  left: 0;
}

.video-info {
  padding: 12px;
}

.video-info h3 {
  margin: 0;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style> 